<template>
  <div class="navigation">
    <div class="navigation-header">
      <h3>导航</h3>
      <el-button-group>
        <el-button @click="startNavigation" :disabled="!canNavigate">
          <el-icon><Position /></el-icon>
          开始导航
        </el-button>
        <el-button @click="stopNavigation" :disabled="!isNavigating">
          <el-icon><Close /></el-icon>
          结束导航
        </el-button>
      </el-button-group>
    </div>

    <div v-if="routeInfo" class="route-info">
      <div class="info-item">
        <span class="label">距离：</span>
        <span>{{ formatDistance(routeInfo.distance) }}</span>
      </div>
      <div class="info-item">
        <span class="label">预计时间：</span>
        <span>{{ formatDuration(routeInfo.duration) }}</span>
      </div>
      <div class="info-item">
        <span class="label">收费：</span>
        <span>{{ routeInfo.toll ? `¥${routeInfo.toll}` : '免费' }}</span>
      </div>
    </div>

    <div v-if="isNavigating" class="navigation-tips">
      <p class="tip">{{ currentTip }}</p>
      <p class="next-tip">{{ nextTip }}</p>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Position, Close } from '@element-plus/icons-vue'

export default {
  name: 'Navigation',
  components: {
    Position,
    Close
  },
  props: {
    startLocation: {
      type: Object,
      required: true
    },
    endLocation: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const isNavigating = ref(false)
    const routeInfo = ref(null)
    const currentTip = ref('')
    const nextTip = ref('')
    const driving = ref(null)

    const canNavigate = computed(() => {
      return props.startLocation && props.endLocation && !isNavigating.value
    })

    // 初始化导航
    const initNavigation = () => {
      AMap.plugin('AMap.Driving', () => {
        driving.value = new AMap.Driving({
          map: window.map,
          panel: false,
          policy: AMap.DrivingPolicy.LEAST_TIME
        })
      })
    }

    // 开始导航
    const startNavigation = () => {
      if (!driving.value) {
        initNavigation()
      }

      const start = [props.startLocation.lng, props.startLocation.lat]
      const end = [props.endLocation.lng, props.endLocation.lat]

      driving.value.search(start, end, (status, result) => {
        if (status === 'complete') {
          routeInfo.value = {
            distance: result.routes[0].distance,
            duration: result.routes[0].time,
            toll: result.routes[0].toll
          }
          isNavigating.value = true
          startRealTimeNavigation(result.routes[0])
        } else {
          ElMessage.error('获取导航路线失败')
        }
      })
    }

    // 实时导航
    const startRealTimeNavigation = (route) => {
      let currentStep = 0
      const steps = route.steps

      const updateTips = () => {
        if (currentStep < steps.length) {
          currentTip.value = steps[currentStep].instruction
          nextTip.value = currentStep + 1 < steps.length ? 
            `下一步：${steps[currentStep + 1].instruction}` : 
            '即将到达目的地'
        }
      }

      updateTips()

      // 监听位置变化
      const watchId = navigator.geolocation.watchPosition(
        (position) => {
          const currentPos = {
            lng: position.coords.longitude,
            lat: position.coords.latitude
          }
          
          // 检查是否到达当前步骤的终点
          const currentStepEnd = steps[currentStep].end_location
          const distance = calculateDistance(
            currentPos,
            { lng: currentStepEnd.lng, lat: currentStepEnd.lat }
          )

          if (distance < 50) { // 50米范围内认为到达
            currentStep++
            updateTips()
          }
        },
        (error) => {
          ElMessage.error('获取位置信息失败')
        },
        {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0
        }
      )

      // 保存watchId以便停止导航时清除
      window.navigationWatchId = watchId
    }

    // 结束导航
    const stopNavigation = () => {
      if (window.navigationWatchId) {
        navigator.geolocation.clearWatch(window.navigationWatchId)
      }
      isNavigating.value = false
      routeInfo.value = null
      currentTip.value = ''
      nextTip.value = ''
      if (driving.value) {
        driving.value.clear()
      }
    }

    // 计算两点之间的距离（米）
    const calculateDistance = (point1, point2) => {
      const R = 6371000 // 地球半径（米）
      const dLat = (point2.lat - point1.lat) * Math.PI / 180
      const dLng = (point2.lng - point1.lng) * Math.PI / 180
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(point1.lat * Math.PI / 180) * Math.cos(point2.lat * Math.PI / 180) * 
        Math.sin(dLng/2) * Math.sin(dLng/2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
      return R * c
    }

    // 格式化距离
    const formatDistance = (meters) => {
      if (meters < 1000) {
        return `${Math.round(meters)}米`
      }
      return `${(meters / 1000).toFixed(1)}公里`
    }

    // 格式化时间
    const formatDuration = (seconds) => {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      
      if (hours > 0) {
        return `${hours}小时${minutes}分钟`
      }
      return `${minutes}分钟`
    }

    return {
      isNavigating,
      routeInfo,
      currentTip,
      nextTip,
      canNavigate,
      startNavigation,
      stopNavigation,
      formatDistance,
      formatDuration
    }
  }
}
</script>

<style scoped>
.navigation {
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.navigation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.navigation-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.route-info {
  margin: 15px 0;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin: 5px 0;
  color: #606266;
}

.info-item .label {
  color: #909399;
}

.navigation-tips {
  margin-top: 15px;
  padding: 10px;
  background: #ecf5ff;
  border-radius: 4px;
}

.tip {
  margin: 5px 0;
  font-size: 16px;
  color: #409eff;
  font-weight: bold;
}

.next-tip {
  margin: 5px 0;
  font-size: 14px;
  color: #606266;
}
</style> 